package com.suthund.frame.exception;


import com.suthund.bean.response.BaseResponse;
import com.suthund.consts.ServiceError;
import com.suthund.util.SendEmailUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/***
 *  Created by 杨康 on 2017/4/18.
 */
@ControllerAdvice
public class HandleException {

    @Resource
    private SendEmailUtil sendEmailUtil;

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 统一处理异常防止异常暴露给调用者
     * 将异常日志形式记录下来
     * @param e 异常
     * @return json
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public BaseResponse handle(Exception e){
        if(e instanceof CheckResultException ){
            CheckResultException check = (CheckResultException) e ;
            return BaseResponse.ResponseFail(e.getMessage(),check.getCode());
        }
        //发送邮件通知系统异常
        String text =getExceptionAllInformation(e);
        sendEmailUtil.sendEmail(text,"系统报错了","北京165网科技有限公司");
        //TODO 后期加上短信提醒或者其他形式提醒...(更多)
        logger.warn("系统异常{}", e);
        return BaseResponse.ResponseFail(ServiceError.UNKNOWN_ERROR);
    }

    private static String getExceptionAllInformation(Exception ex){
        String sOut = "报错信息如下请快速排查：";
        StackTraceElement[] trace = ex.getStackTrace();
        sOut += "\t " + ex+ "\r\n";
        for (StackTraceElement s : trace) {
            sOut += "\tat " + s + "\r\n";
        }
        return sOut;
    }
}
